<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\controllers;

use app\models\MemberRecorder;
use app\models\MessageRecorder;
use app\models\SetRecorder;
use yii\web\Controller;

class BaseController extends Controller{
    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {
        if(\Yii::$app->admin->isGuest){
            $result = ['result'=>-1,"data"=>'请先登录'];
            echo json_encode($result);
            return false;
        }
        $set_model = SetRecorder::find()->where('set_type=1')->one();
        $set_param = empty($set_model->content)?[]:json_decode($set_model->content,true);
        $param = \Yii::$app->params;
        $param = array_merge($set_param,$param);
        \Yii::$app->params=$param;
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }



    public function send_message($message,$user_id=0){
        if(empty($message)||!is_array($message)){
            return;
        }
        $appid = \Yii::$app->params['appid'];
        $secret = \Yii::$app->params['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $token_arr = file_get_contents($url);
        $token_arr = json_decode($token_arr,true);
        if(empty($token_arr['access_token'])){
            return;
        }

        $user = MemberRecorder::find()->where('id='.$user_id)->one();
        if(empty($user)){
            return;
        }
        $message['touser'] = $user->openid;
        $post = json_encode($message);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token_arr['access_token'];
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
        @curl_exec($curl);
    }


    public function get_message($type=0){
        $model = MessageRecorder::find()->where('message_cate='.$type)->one();
        if(empty($model)){
            return [];
        }
        $data['template_id'] = $model->message_id;
        $data['page'] = "page/page/index";
        $data['data']= json_decode($model->message_content,true);
         return $data;
    }
}